import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_utils/file_utils.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../entry.dart';
import '../common/flatPanel.dart';
import '../utils/screw.dart';

class TextEditPage extends StatefulWidget {
  @override
  _TextEditPageState createState() => _TextEditPageState();
}

enum EditFlag { Initial, Normal, Edit }

class _TextEditPageState extends State<TextEditPage> {
  final _content = TextEditingController();
  List<String> _fileList = [];
  final entry = Entry.TextEdit;
  String _dirPath = '';
  String _fileName = '';
  String _filePath = '';
  String _previousContent = '';
  var _editFlag = EditFlag.Initial; // 0 : 首次运行, 1: 编辑中 2： 已保存

  @override
  void initState() {
    super.initState();

    _fileName = '${Screw.genDateString()}.txt';
    _fileList.add(_fileName);
  }

  void _load() async {
    if (_fileName.isEmpty) return;

    if (!_fileName.endsWith('.txt')) _fileName = _fileName + '.txt';

    if (_dirPath.isEmpty) _dirPath = await Screw.getUserFilePath('flutter');

    _filePath = Screw.joinPath(_dirPath, _fileName);
    var file = File(_filePath);
    if (await file.exists()) {
      _previousContent = await file.readAsString();
      if (_previousContent.isNotEmpty) _content.text = _previousContent;
    } else {
      await file.create(recursive: true);
    }
    setState(() {
      _editFlag = EditFlag.Normal;
    });
  }

  void _save() async {
    if (_fileName.isEmpty) return;

    _filePath = Screw.joinPath(_dirPath, _fileName);

    if (_previousContent == _content.text) return;

    _previousContent = _content.text;
    await File(_filePath).writeAsString(_previousContent);
    Screw.popup(context, '文件已保存到: $_filePath');
    setState(() {
      _editFlag = EditFlag.Normal;
    });
  }

  void _updateFileList() async {
    if (_dirPath.isEmpty) _dirPath = await Screw.getUserFilePath('flutter');

    var appDir = Directory(_dirPath);

    if (await appDir.exists()) {
      var items = await appDir
          .list()
          .map((event) => FileUtils.basename(event.path))
          .toList();

      if (items.isNotEmpty)
        setState(() {
          _fileList = items;
        });
    }
  }

  void _showInputDialog() async {
    var content = TextEditingController();
    content.text = _fileName;
    showDialog(
        context: context,
        builder: (context) {
          var child = FlatPanel(
            child: Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: TextField(
                    controller: content,
                    decoration: InputDecoration(
                        icon: FaIcon(FontAwesomeIcons.file),
                        hintText: '文件名',
                        hintStyle: TextStyle(fontSize: 24)),
                  ),
                ),
                IconButton(
                  icon: FaIcon(FontAwesomeIcons.solidPaperPlane),
                  onPressed: () {
                    if (content.text.isNotEmpty) _fileName = content.text;
                    _load();
                    Navigator.of(context).pop();
                  },
                ),
              ],
            ),
          );
          return Dialog(child: child);
        });
  }

  Widget _updateFloatingActionButton() {
    switch (_editFlag) {
      case EditFlag.Initial:
        return FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: _showInputDialog,
        );
      case EditFlag.Edit:
        return FloatingActionButton(
          child: Icon(Icons.save_alt),
          onPressed: _save,
        );
      default:
        return FloatingActionButton(
          child: Icon(Icons.auto_stories),
          onPressed: () {
            if (_content.text.isEmpty)
              Screw.popup(context, '内容不能为空！');
            else if (_previousContent != _content.text)
              setState(() {
                _editFlag = EditFlag.Edit;
              });
          },
        );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(entry),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add),
            onPressed: _showInputDialog,
          ),
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: _updateFileList,
          ),
          IconButton(
            icon: Icon(Icons.cleaning_services),
            onPressed: () {
              if (_content.text.isNotEmpty) _content.clear();
            },
          )
        ],
      ),
      body: FlatPanel(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: DropdownButton(
                    items: _fileList
                        .map((e) => DropdownMenuItem(child: Text(e), value: e))
                        .toList(),
                    onChanged: (v) {
                      _fileName = v;
                      _load();
                    },
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Text(_fileName, style: TextStyle(fontSize: 18)),
                ),
              ],
            ),
            TextField(
              controller: _content,
              keyboardType: TextInputType.multiline,
              maxLines: null,
            ),
          ],
        ),
      ),
      floatingActionButton: _updateFloatingActionButton(),
    );
  }
}
